<?php
/**
 * 获取系统中的数据库
 * @param string $dbName 数据库名
 * @param string $dbType 数据库类型  sqlite mysql
 * @param array $cs array('host'=>'localhost:3306','user'=>'root','password'=>'123456')
 * @return QAppDB
 */
function M($dbName = "", $dbType = "sqlite", $cs = array())
{
    global $dbConfig;
    if ($dbName) {
        if (!isset($GLOBALS['dbs'])) {
            $GLOBALS['dbs'] = array();
        }

        if ($dbType == "sqlite") {
            $dnName_md5 = 'db_' . md5($dbName);
            $db_arr = array('database' => 'sqlitepdo', 'dbfile' => DBDir . $dbName . '.db');
        } else {
            if (!is_array($cs)) {
                $cs = array();
            }
            $db_arr = array('database' => 'mysqlpdo', 'host' => '', 'dbname' => '', 'user' => '', 'password' => '');
            $db_arr['host'] = isset($cs['host']) ? ($cs['host']) : $dbConfig['mysql']['host'] . ":" . $dbConfig['mysql']['port'];
            $db_arr['user'] = isset($cs['user']) ? ($cs['user']) : $dbConfig['mysql']['user'];
            $db_arr['password'] = isset($cs['password']) ? ($cs['password']) : $dbConfig['mysql']['password'];
            $db_arr['dbname'] = $dbName;
            $dnName_md5 = 'db_' . md5($db_arr['host'] . $dbName);
        }

        if (!isset($GLOBALS['dbs'][$dnName_md5])) {
            $GLOBALS['dbs'][$dnName_md5] = new QAppDB();
            $GLOBALS['dbs'][$dnName_md5]->connect($db_arr);
        }
        return $GLOBALS['dbs'][$dnName_md5];

    } else {
        global $site_db;
        if (!isset($GLOBALS['db'])) {
            $GLOBALS['db'] = new QAppDB();
            $ret = $GLOBALS['db']->connect($site_db);
            if ($ret !== true) {
                die($ret);
            }
        }
        return $GLOBALS['db'];
    }
}


/**
 * 返回MedooDB对象，自动单例
 * @param null $config
 * @return Medoo\medoo
 */
function getMedoo($config = null)
{
    global $site_db, $dbConfig;
    if ($config) {
        $key = "medoo_" . md5(json_encode($config));
        if (isset($_SERVER[$key])) {
            return $_SERVER[$key];
        }
        $database = new Medoo\medoo($config);
        $_SERVER[$key] = $database;
    } else {
        $key = "medoo_main";
        if (isset($_SERVER[$key])) {
            return $_SERVER[$key];
        }
        if ($dbConfig['type'] == "sqlite") {
            $database = new Medoo\medoo([
                'database_type' => $dbConfig['type'],
                'prefix' => TableEx,
                'database_file' => $site_db['dbfile']
            ]);
        } else if ($dbConfig['type'] == "mysql") {
            $database = new Medoo\medoo([
                'database_type' => $dbConfig['type'],
                'prefix' => TableEx,
                'database_name' => $dbConfig['mysql']['dbname'],
                'server' => $dbConfig['mysql']['host'],
                'username' => $dbConfig['mysql']['user'],
                'password' => $dbConfig['mysql']['password'],
                // [optional]
                'charset' => 'utf8mb4',
                'port' => $dbConfig['mysql']['port'],
            ]);

        } else {
            exit("unsupporte database type:" . $dbConfig['type']);
        }
    }

    $_SERVER[$key] = $database;
    return $database;
}


/**
 * 创建jsondb实例
 * @param string $dbname 库名
 * @return \Jajo\jsondb|mixed|null
 */
function getJsonDB($dbname = '')
{
    $dbpath = AppDir . 'data/jsondb/';
    if (empty($dbname)) {
        $dbname = 'main';
    }
    $dbpath = $dbpath . $dbname . '/';
    if (!file_exists($dbpath)) {
        file_mkdir($dbpath, 0777, true);
    }
    $jsondb = getGlobals('jsondb_' . $dbpath);
    if ($jsondb) return $jsondb;
    $jsondb = new \Jajo\JSONDB($dbpath);
    setGlobals('jsondb_' . $dbpath, $jsondb);
    return $jsondb;
}

/**
 * 添加表前缀
 * @param string $table
 * @return string
 */
function tableex($table = '')
{
    if (substr($table, 0, strlen(TableEx)) == TableEx) {
        return $table;
    } else {
        return TableEx . $table;
    }
}

/**
 * 移除表前缀
 * @param string $table
 * @return false|string
 */
function untableex($table = '')
{
    if (substr($table, 0, strlen(TableEx)) == TableEx) {
        return substr($table, strlen(TableEx));
    } else {
        return $table;
    }
}


/**
 * 转义写入数据库时的值
 * @param $str
 * @return mixed
 */
function dbstr($str)
{
    global $site_db;
    $str = str_replace("'", "''", $str);
    if ($site_db['database'] == 'mysqlpdo' || $site_db['database'] == 'mysql') {
        $str = str_replace('\\', '\\\\', $str);
    }
    return $str;
}
